/*
 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package checkers.database;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author artinshahverdian
 */
public class ConnectionPool {

    private static ConnectionPool instance;
    private BoneCP connectionPool = null;

    private ConnectionPool(String databaseAddress, String databaseName,
            String username, String password) throws SQLException, ClassNotFoundException {


        String url = "jdbc:mysql://" + databaseAddress + "/" + databaseName;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException ex) {
            Logger.getLogger(MySQLGameOperations.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }

        // setup the connection pool
        BoneCPConfig config = new BoneCPConfig();
        config.setJdbcUrl(url); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
        config.setUsername(username);
        config.setPassword(password);
        config.setMinConnectionsPerPartition(5);
        config.setMaxConnectionsPerPartition(20);
        config.setPartitionCount(2);

        connectionPool = new BoneCP(config); // setup the connection pool

    }

    public static ConnectionPool createInstance(String databaseAddress,
            String databaseName, String username,
            String password) throws SQLException, ClassNotFoundException {

        if (instance == null) {
            instance = new ConnectionPool(databaseAddress, databaseName, username, password);
        }
        return instance;


    }

    public static ConnectionPool getInstance() throws Exception {
        if (instance != null)
            return instance;
        throw new Exception("Initialize connection pool before using it");
    }

    public Connection getConnection() throws SQLException {
        return connectionPool.getConnection();
    }

    public void shutDown() {
        connectionPool.shutdown();
    }
}
